import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { HYDRATE } from "next-redux-wrapper";
import {
  getAllProduct,
  getHomeInfo,
  getHotProduct,
  getSearchSuggest,
} from "../../service/homeService";
import { IHomeInitialState } from "../../type/homeType";

const homeSlice = createSlice({
  name: "homeStore",
  initialState: {
    counter: 5,
    navbar: {},
    banners: {},
    categorys: {},
    recommends: {},
    hotProduct: {},
    digitalData: {},
    allProduct: {},
  } as IHomeInitialState,
  reducers: {},
  extraReducers(builder) {
    builder
      .addCase(HYDRATE, (state, action: any) => {
        return {
          ...state,
          ...action.payload.home,
        };
      })
      .addCase(fetchSearchSuggest.fulfilled, (state, { payload }) => {
        state.navbar = payload;
      })
      .addCase(fetchHomeInfoAction.fulfilled, (state, { payload }) => {
        state.banners = payload.banners;
        state.categorys = payload.categorys;
        state.recommends = payload.recommends;
        state.digitalData = payload.digitalData;
      })
      .addCase(fetchHotProductAction.fulfilled, (state, { payload }) => {
        state.hotProduct = payload.hotProduct;
      })
      .addCase(fetchAllProductAction.fulfilled, (state, { payload }) => {
        state.allProduct = payload.allProduct;
      });
  },
});

// 异步的action,搜索数据
export const fetchSearchSuggest = createAsyncThunk(
  "fetchSearchSuggest",
  async () => {
    // 发送网络请求
    const res = await getSearchSuggest();
    return res.data;
  }
);
// 首页数据
export const fetchHomeInfoAction = createAsyncThunk(
  "fetchHomeInfoAction",
  async () => {
    const res = await getHomeInfo();
    return res.data;
  }
);
// 编辑推荐
export const fetchHotProductAction = createAsyncThunk(
  "fetchHotProductAction",
  async () => {
    const res = await getHotProduct();
    return res.data;
  }
);
// 热门商品
export const fetchAllProductAction = createAsyncThunk(
  "fetchAllProductAction",
  async () => {
    const res = await getAllProduct();
    return res.data;
  }
);

export default homeSlice.reducer;
